const { goodsModel } = require('../../models/goods')
const fs = require('fs')
const path = require('path')

function deleteFile(url) {
  let urlto = path.resolve(__dirname, '../../public', url)
  let ret = fs.existsSync(urlto)
  if (ret) {
    fs.unlinkSync(urlto)
    return true
  }
  else return false
}

module.exports = class Goods {
  // 获取商品列表数据
  static async listGoods(ctx) {
    let query = ctx.query;
    //默认第一页
    let page = query.page ? parseInt(query.page) : 1;
    // 默认查询10条
    let size = query.size ? parseInt(query.size) : 10;
    let name = ctx.query.name || '';
    let cate = ctx.query.cate || '';

    let params = {}
    cate ? params['cate'] = cate : '';
    name ? params['title'] = new RegExp(name, 'g') : ''


    // 分页查询数据库
    let data = await goodsModel.find(params).skip((page - 1) * size).limit(size);
    // 获取总条数
    let count = await goodsModel.find(params).count()

    ctx.body = {
      code: 200,
      msg: '获取成功',
      count: count,
      data: data
    }
  }
  // 设置或添加商品数据
  static async addGoods(ctx) {
    // 获取数据
    let {_id, title, info, imageUrl, price, tag, chose, cate, swiperImg, date, detail, state,hot } = ctx.request.body;

    // 判断是否有必填项未填
    if (!(title && imageUrl && price && date)) {
      ctx.body = { code: 300, msg: '有未填 项' }
      return
    }
    // 入参
    let params = {
      title,info,imageUrl,price,
      tag: tag.split('|'),
      chose, cate,
      swiperImg: swiperImg.split('|'),
      detail, date, state, hot
    }
    let data = null
    if (!_id) {
      // 添加数据
      data = await goodsModel.insertMany(params);
    } else {
      // 覆盖数据
      data = await goodsModel.updateOne({ _id: _id }, { $set: params });
    }

    if ((data && data.length) || (data.n && data.ok))
      ctx.body = { code: 200, msg: '成功', data }
    else
      ctx.body = { code: 400, msg: '失败' }
  }
  // 删除商品数据
  static async deleteGoods(ctx) {
    let { id } = ctx.request.body;
    let bool = null;
    console.log(id)
    // 删除多条数据
    if (Object.prototype.toString.call(id) === '[object Array]') {
      for (let i = 0; i < id.length; i++) {
        let arr = await goodsModel.find({ _id: id[i] }, { swiperImg: 1 })
        bool = await goodsModel.deleteMany({ _id: id[i] })
        // 删除图片
        let imglist = arr[0].swiperImg
        for (let i = 0; i < imglist.length; i++) {
          deleteFile(imglist[i])
        }
      }
    }
    // 删除一条数据
    else {
      let arr = await goodsModel.find({ _id: id }, { swiperImg: 1 })
      bool = await goodsModel.deleteMany({ _id: id })

      // 删除图片
      let imglist = arr[0].swiperImg
      for (let i = 0; i < imglist.length; i++) {
        deleteFile(imglist[i])
      }
    }
    ctx.body = { code: 200, msg: '删除成功' }
  }

  // 查询商品详情
  static async getGoodsDetails(ctx) {
    let { id } = ctx.query

    let data = await goodsModel.find({ _id: id })

    if (data.length)
      ctx.body = { code: 200, msg: '查询成功', data: data[0] }
    else
      ctx.body = { code: 400, msg: '查询失败', data: {} }
  }

  // 上传图片
  static async uploadImg(ctx) {
    let file = ctx.request.files.imgFile;
    // console.log(file)

    let next = file.name.split('.')
    let url = `cdn/${Date.now()}.${next[next.length - 1]}`
    let urlto = path.resolve(__dirname, '../../public', url)

    // 流式读取并写入
    const readstream = fs.createReadStream(file.path);
    await readstream.pipe(fs.createWriteStream(urlto));

    ctx.body = { code: 200, msg: '上传成功', status: "success", data: { url } }
  }
  // 删除商品图片
  static async deleteImg(ctx) {
    let { url } = ctx.request.body;
    deleteFile(url)
    ctx.body = { code: 200, msg: '删除成功' }
  }

  // 设置商品状态
  static async setGoodsState(ctx) {
    let { id ,state} = ctx.request.body
    
    let data = await goodsModel.updateOne({ _id: id }, { $set: { state } })
    
    if(data.n&&data.ok){
      ctx.body = { code: 200, msg: '修改成功' }
    } else {
      ctx.body = { code: 400, msg: '修改失败' }
    }
  }

}